<template>
    <div class="phone-container">
        <!-- 手机外壳 -->
        <div class="phone-frame">
            <!-- 音量键 -->
            <div class="volume-buttons">
                <div class="volume-up"></div>
                <div class="volume-down"></div>
            </div>

            <!-- 开机键 -->
            <div class="power-button"></div>

            <!-- 静音开关 -->
            <div class="mute-switch"></div>

            <!-- 手机屏幕内容 -->
            <div class="phone-screen">
                <div class="order-confirm-container">
                    <!-- 顶部导航栏 -->
                    <van-nav-bar title="开单确认" left-arrow fixed placeholder @click-left="goBack" class="custom-nav">
                        <template #right>
                            <van-icon name="ellipsis" size="20" />
                            <van-icon name="eye-o" size="20" style="margin-left: 12px" />
                        </template>
                    </van-nav-bar>

                    <!-- 可滚动的内容区域 -->
                    <div class="scrollable-content">
                        <!-- 申请信息 -->
                        <div class="section info-section">
                            <div class="section-title">申请信息</div>
                            <div class="info-row">
                                <span>申请医院</span>
                                <span class="info-value">{{ hospitalInfo.name }}</span>
                            </div>
                            <div class="info-row">
                                <span>申请人</span>
                                <span class="info-value">{{ userInfo.name }} ></span>
                            </div>
                        </div>

                        <!-- 申请原因 -->
                        <div class="section reason-section">
                            <div class="section-title required">申请原因</div>
                            <van-field v-model="reason" type="textarea" rows="3" maxlength="200" show-word-limit
                                placeholder="请输入项目申请原因用于医生更准确判断，不少于10字" class="reason-input" />
                        </div>

                        <!-- 申请项目 -->
                        <div class="section items-section">
                            <div class="section-title">申请项目</div>
                            <div class="item-list">
                                <div class="item-row" v-for="item in orderItems" :key="item.id">
                                    <div class="item-main">
                                        <span v-if="item.type === 'medicine'" class="tag tag-medicine">药</span>
                                        <span v-if="item.type === 'examination'" class="tag tag-exam">查</span>
                                        <span v-if="item.type === 'test'" class="tag tag-test">检</span>
                                        <span class="item-name">{{ item.name }}</span>
                                        <span class="item-price">¥ {{ item.price }}</span>
                                    </div>
                                    <div class="item-detail">
                                        <span class="item-qty">数量：{{ item.quantity }}{{ item.unit }}</span>
                                        <span v-if="item.type === 'medicine'" class="item-labels">
                                            <span class="label label-rx">处方药</span>
                                            <span v-if="item.limit" class="label label-limit">限购{{ item.limit }}{{
                                                item.unit }}</span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="total-row">
                                <span>合计：</span>
                                <span class="total-price">¥ {{ totalAmount.toFixed(2) }}</span>
                            </div>
                        </div>

                        <!-- 确认按钮 - 在申请项目下面 -->
                        <div class="confirm-btn-section">
                            <button @click="showSuccessModal" class="confirm-btn">
                                确认申请
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 成功提示弹框 - 移到根级别 -->
    <van-popup v-model:show="showModal" :close-on-click-overlay="false" class="success-modal">
        <div class="modal-content">
            <div class="modal-title">申请提示</div>
            <div class="modal-message">
                项目申请已提交，请耐心等待审核结果，可在开单记录中查询审核状态
            </div>
            <div class="modal-actions">
                <button @click="goToOrderRecord" class="modal-btn">
                    去查看
                </button>
            </div>
        </div>
    </van-popup>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { getHospitalBranchList } from '@/api/hospital'
import { createOrder } from '@/api/order'
import type { HospitalBranch } from '@/types/api'

const router = useRouter()
const route = useRoute()

// 申请原因
const reason = ref('')

// 用户信息
const userInfo = ref({
    name: '王小柯',
    idCard: '510123199001011234'
})

// 医院信息
const hospitalInfo = ref<HospitalBranch>({
    id: 1,
    name: '四川省保健院北苑',
    address: '四川省成都市锦江区',
    phone: '028-12345678',
    isEnabled: true,
    sortOrder: 1,
    isDeleted: false,
    createdTime: new Date(),
    updatedTime: null
})

// 订单项目数据
const orderItems = ref<any[]>([])
const totalAmount = ref(0)

// 弹窗状态
const showModal = ref(false)

// 获取医院信息
const fetchHospitalInfo = async () => {
    try {
        const response = await getHospitalBranchList()
        if (response.code === 100 && response.data && response.data.length > 0) {
            hospitalInfo.value = response.data[0] // 使用第一个院区作为默认
        }
    } catch (error) {
        console.error('获取医院信息失败:', error)
    }
}

// 处理从上一页传递的数据
const processOrderData = () => {
    const dataParam = route.query.data
    if (dataParam && typeof dataParam === 'string') {
        try {
            const orderData = JSON.parse(dataParam)
            orderItems.value = orderData.selectedItems || []
            totalAmount.value = orderData.totalAmount || 0

            console.log('接收到的订单数据:', orderData)
            console.log('订单项目:', orderItems.value)
            console.log('总金额:', totalAmount.value)
        } catch (error) {
            console.error('解析订单数据失败:', error)
            showToast('数据解析失败')
        }
    } else {
        console.log('没有接收到订单数据，使用默认数据')
        // 如果没有数据，使用默认数据
        orderItems.value = [
            { id: 1, name: '新冠预防中药（正常人群）', price: 11.80, quantity: 1, unit: '剂', type: 'medicine', limit: 5 },
            { id: 2, name: '云南白药胶囊 0.5g*20片', price: 10.08, quantity: 1, unit: '盒', type: 'medicine' },
            { id: 3, name: '动态心电图', price: 150.00, quantity: 1, unit: '次', type: 'examination' },
            { id: 4, name: '血常规', price: 29.12, quantity: 1, unit: '次', type: 'test' }
        ]
        totalAmount.value = 201.00
    }
}

// 返回上一页
const goBack = () => {
    router.back()
}

// 跳转到订单记录页面
const goToOrderRecord = () => {
    router.push('/order-record')
    showModal.value = false
}

// 显示成功弹窗
const showSuccessModal = async () => {
    console.log('按钮被点击了')

    // 先验证表单
    if (!reason.value.trim()) {
        showToast('请输入申请原因')
        return
    }

    if (reason.value.length < 10) {
        showToast('申请原因不能少于10字')
        return
    }

    try {
        console.log('开始准备订单数据...')

        // 获取API基础URL
        const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5175'
        console.log('API基础URL:', apiBaseUrl)

        // 准备订单数据
        const orderData = {
            hospitalBranchId: hospitalInfo.value.id,
            patientName: userInfo.value.name,
            patientIdCard: userInfo.value.idCard,
            applicationReason: reason.value,
            items: orderItems.value.map(item => ({
                checkItemId: item.id,
                quantity: item.quantity
            }))
        }

        console.log('订单数据:', orderData)
        console.log('完整API URL:', `${apiBaseUrl}/api/OrderRecordCreateOrderRecord`)

        // 调用后端API创建订单
        console.log('开始调用API...')
        const response = await createOrder(orderData)
        console.log('API响应:', response)

        if (response.code === 100) {
            console.log('API调用成功，显示弹框')
            showModal.value = true
        } else {
            console.error('API调用失败:', response.message)
            showToast(response.message || '申请提交失败')
        }
    } catch (error) {
        console.error('创建订单失败:', error)
        showToast('申请提交失败，请重试')
    }
}

onMounted(() => {
    processOrderData()
    fetchHospitalInfo()
})
</script>

<style scoped>
/* 手机容器 */
.phone-container {
    min-height: 100vh;
    background: #f8f9fa;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    /* 确保容器不会影响手机框架 */
    overflow: hidden;
}

/* 手机外壳 */
.phone-frame {
    position: relative;
    width: 375px;
    height: 812px;
    background: #1a1a1a;
    border-radius: 40px;
    padding: 8px;
    box-shadow:
        0 0 0 2px #2a2a2a,
        0 20px 40px rgba(0, 0, 0, 0.3),
        inset 0 0 0 1px #3a3a3a;
    /* 确保框架内容不溢出 */
    overflow: hidden;
}

/* 音量键 */
.volume-buttons {
    position: absolute;
    left: -2px;
    top: 120px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    z-index: 10;
}

.volume-up,
.volume-down {
    width: 4px;
    height: 30px;
    background: linear-gradient(to bottom, #2a2a2a, #1a1a1a);
    border-radius: 2px;
    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.1),
        0 1px 2px rgba(0, 0, 0, 0.3);
}

/* 开机键 */
.power-button {
    position: absolute;
    right: -2px;
    top: 120px;
    width: 4px;
    height: 60px;
    background: linear-gradient(to bottom, #2a2a2a, #1a1a1a);
    border-radius: 2px;
    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.1),
        0 1px 2px rgba(0, 0, 0, 0.3);
}

/* 静音开关 */
.mute-switch {
    position: absolute;
    left: -2px;
    top: 200px;
    width: 4px;
    height: 25px;
    background: linear-gradient(to bottom, #2a2a2a, #1a1a1a);
    border-radius: 2px;
    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.1),
        0 1px 2px rgba(0, 0, 0, 0.3);
}

/* 手机屏幕 */
.phone-screen {
    width: 100%;
    height: 100%;
    background: #000;
    border-radius: 32px;
    overflow: hidden;
    position: relative;
    display: flex;
    flex-direction: column;
}

.order-confirm-container {
    height: 100%;
    background: #f8f9fa;
    padding-bottom: 20px;
    position: relative;
    display: flex;
    flex-direction: column;
    /* 允许内容滚动但限制在框架内 */
    overflow-y: auto;
}

.scrollable-content {
    flex: 1;
    padding-bottom: 20px;
    /* 确保内容区域有足够空间 */
    min-height: calc(100vh - 200px);
}

.custom-nav {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

:deep(.van-nav-bar__title) {
    color: white;
    font-weight: 500;
}

:deep(.van-nav-bar__left .van-icon),
:deep(.van-nav-bar__right .van-icon) {
    color: white;
}

.section {
    background: #fff;
    border-radius: 12px;
    margin: 16px 16px 0 16px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
    color: #222;
}

.section-title.required:after {
    content: '*';
    color: #e74c3c;
    margin-left: 2px;
}

.info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 15px;
    color: #333;
    margin-bottom: 8px;
    padding: 8px 0;
}

.info-value {
    color: #222;
    font-weight: 500;
}

.reason-section {
    margin-top: 16px;
}

.reason-input {
    background: #f7f7fa;
    border-radius: 8px;
}

:deep(.van-field__control) {
    background: #f7f7fa;
    border-radius: 8px;
    padding: 12px;
    min-height: 80px;
}

.items-section {
    margin-top: 16px;
}

.item-list {
    margin-bottom: 8px;
}

.item-row {
    border-bottom: 1px solid #f0f0f0;
    padding: 12px 0;
}

.item-row:last-child {
    border-bottom: none;
}

.item-main {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
}

.tag {
    display: inline-block;
    font-size: 12px;
    border-radius: 4px;
    padding: 2px 6px;
    color: #fff;
    font-weight: 500;
    min-width: 20px;
    text-align: center;
}

.tag-medicine {
    background: #4fc3f7;
}

.tag-exam {
    background: #ff7043;
}

.tag-test {
    background: #e74c3c;
}

.item-name {
    font-size: 15px;
    color: #333;
    font-weight: 500;
    flex: 1;
}

.item-price {
    color: #e74c3c;
    font-size: 15px;
    font-weight: 500;
    flex-shrink: 0;
}

.item-detail {
    font-size: 13px;
    color: #888;
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.item-qty {
    color: #666;
}

.item-labels {
    margin-left: 8px;
}

.label {
    display: inline-block;
    font-size: 11px;
    border-radius: 3px;
    padding: 1px 4px;
    margin-right: 4px;
}

.label-rx {
    background: #e3f2fd;
    color: #4285f4;
}

.label-limit {
    background: #fdecea;
    color: #e74c3c;
}

.total-row {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    margin-top: 16px;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
}

.total-price {
    color: #e74c3c;
    margin-left: 8px;
}

.confirm-btn-section {
    margin: 16px 16px 0 16px;
    padding: 16px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.confirm-btn {
    width: 100%;
    height: 48px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 24px;
    color: white;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
}

/* 成功弹窗样式 */
.success-modal {
    width: 80%;
    border-radius: 16px;
    overflow: hidden;
    background: #fff;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
    z-index: 9999;
}

:deep(.van-popup) {
    z-index: 9999;
}

.modal-content {
    padding: 24px;
    text-align: center;
}

.modal-title {
    font-size: 20px;
    font-weight: 700;
    color: #333;
    margin-bottom: 12px;
}

.modal-message {
    font-size: 15px;
    color: #666;
    line-height: 1.6;
    margin-bottom: 24px;
}

.modal-actions {
    display: flex;
    justify-content: center;
    gap: 15px;
}

.modal-btn {
    width: 120px;
    height: 40px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 20px;
    color: white;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 手机外壳响应式 */
@media (max-width: 420px) {
    .phone-frame {
        width: 100%;
        height: 100vh;
        border-radius: 0;
        padding: 0;
    }

    .phone-screen {
        border-radius: 0;
    }

    .volume-buttons,
    .power-button,
    .mute-switch {
        display: none;
    }
}
</style>